<?php

class TaskPresenter extends BasePresenter
{

	/**
	 * @persistent
	 */
	public $orderBy = 'deadline';
	/**
	 * @persistent
	 */
	public $direction = 'asc';
	/**
	 * @persistent
	 */
	public $project = 0;
	/**
	 * @persistent
	 */
	public $creator = 0;
	/**
	 * @persistent
	 */
	public $worker = 0;
	/**
	 * @persistent
	 */
	public $taskType = 0;

	private $id;
	
	public function renderDefault()
	{
		$tasksModel = $this->context->models->tasks;
		$projectsModel = $this->context->models->projects;
		$taskContextModel = $this->context->models->taskContext;
		$tasks = $tasksModel->getTasks(false,array('project.closed'=>'no'));

		$this->orderTasks($tasks);

		if ($this->project != 0)
			$tasks->where('task.project_id', $this->project);
		if ($this->creator != 0)
			$tasks->where('task.creator_id', $this->creator);
		if ($this->worker != 0)
			$tasks->where('task.worker_id', $this->worker);
		if ($this->taskType != 0)
			$tasks->where('task.task_type_id', $this->taskType);
		
		$this->template->tasks = $tasks;
		$priority = $this->presenter->context->models->taskContext;
		$this->template->priorities = $priority->getPriorities();
		
		$this->template->workers = $tasksModel->getUsedWorkers();
		$this->template->creators = $tasksModel->getUsedCreators();
		$this->template->projects = $projectsModel->getPublicProjects($this->user->id);
		$this->template->taskTypes = $taskContextModel->getTypes();
	}

	public function renderMyTasks()
	{
		$userId = $this->getUser()->getId();
		$tasksModel = $this->context->models->tasks;
		$projectsModel = $this->context->models->projects;
		$taskContextModel = $this->context->models->taskContext;
		
		$tasks = $tasksModel->getTasks($userId);
		$this->orderTasks($tasks);

		$this->template->tasks = $tasks;
		
		$priority = $this->presenter->context->models->taskContext;
		$this->template->priorities = $priority->getPriorities();
		$this->template->workers = $tasksModel->getUsedWorkers();
		$this->template->creators = $tasksModel->getUsedCreators();
		$this->template->projects = $projectsModel->getPublicProjects($userId);
		$this->template->taskTypes = $taskContextModel->getTypes();
	}

	public function renderAssignedTasks()
	{
		$tasksModel = $this->context->models->tasks;
		$projectsModel = $this->context->models->projects;
		$taskContextModel = $this->context->models->taskContext;
		$tasks = $tasksModel->getAssignedTasks($this->user->id,array('project.closed'=>'no'));

		$this->orderTasks($tasks);

		if ($this->project != 0)
			$tasks->where('task.project_id', $this->project);
		if ($this->worker != 0)
			$tasks->where('task.worker_id', $this->worker);
		if ($this->taskType != 0)
			$tasks->where('task.task_type_id', $this->taskType);
		
		$this->template->tasks = $tasks;
		$priority = $this->presenter->context->models->taskContext;
		$this->template->priorities = $priority->getPriorities();
		
		$this->template->workers = $tasksModel->getUsedWorkers();
		$this->template->creators = $tasksModel->getUsedCreators();
		$this->template->projects = $projectsModel->getPublicProjects($this->user->id);
		$this->template->taskTypes = $taskContextModel->getTypes();
	}

	public function handleOrderBy($by)
	{

		$allowOrderBy = array('priority', 'name', 'project', 'creator', 'worker', 'deadline', 'completed');

		if (in_array($by, $allowOrderBy))
		{
			if ($this->orderBy == $by && $this->direction == 'asc')
				$this->direction = 'desc';
			else
				$this->direction = 'asc';

			$this->orderBy = $by;
		}

		if (!$this->isAjax())
		{
			$this->redirect('this');
		} else
		{
			$this->invalidateControl("tasks");
		}
	}

	public function handleFilter($project,$creator,$worker,$taskType)
	{
		$this->worker = $worker;
		if (!$this->isAjax())
		{
			$this->redirect('this');
		} else
		{
			$this->invalidateControl("tasks");
		}
	}

	public function renderTask($id)
	{
		$this->id = $id;
		$task = $this->context->models->task->find($id);
		$this->template->task = $task->getTask();
		$this->template->history = $task->getHistory();
		$this->template->prerequisites = $task->getPrerequisites();
		$this->template->preconditionFor = $task->getPreconditionFor();
		$this->template->comments = $task->getComments();
		$this->template->projectResource = new \Tasker\Authorization\ProjectResource($task->task['project_id']);
	}

	private function orderTasks($tasks)
	{
		if ($this->direction != 'asc' && $this->direction != 'desc')
			$this->direction = 'asc';
		$tasks->order("IF(task_status.completed='no',0,1)");
		switch ($this->orderBy)
		{
			case 'priority':
				$tasks->order('task_priority.priority ' . $this->direction);
				break;
			case 'name':
				$tasks->order('name ' . $this->direction);
				break;
			case 'project':
				$tasks->order('project.name ' . $this->direction);
				break;
			case 'worker':
				$tasks->order('worker.surname ' . $this->direction . ', worker.name ' . $this->direction);
				break;
			case 'creator':
				$tasks->order('creator.surname ' . $this->direction . ', creator.name ' . $this->direction);
				break;
			case 'deadline':
				if ($this->direction == 'asc')
					$tasks->order('IF(ISNULL(task.deadline),1,0),task.deadline asc');
				else
					$tasks->order('IF(ISNULL(task.deadline),0,1),task.deadline desc');
				break;
			case 'completed':
				$tasks->order('completed ' . $this->direction);
				break;
		}
		return $tasks;
	}

	public function renderEditTask($id)
	{
		$this->template->id = $id;
	}

	protected function createComponentCommentForm($name)
	{
		$form = new \Nette\Application\UI\Form($this,$name);
		$form->addTextArea('text', null, 85, 7);
		$form->addSubmit('save','Vložit komentář');
		$form->addHidden('user_id',$this->user->id);
		$form->addHidden('task_id',$this->id);
		
		$form->onSuccess[] = callback($this,'commentFormSubmitted');
		return $form;
	}
	
	public function commentFormSubmitted($form)
	{
		$values = $form->getValues();
		$tasksModel = $this->context->models->tasks;
		$values['date'] = new DateTime();
		if($tasksModel->addComment($values) !== null)
		{
			$this->flashMessage('Komentář byl úspěšně vložen.');
			$this->redirect('this');
		}else{
			$this->flashMessage('Chyba při vkládání komentáře.');
		}
	}
	
	protected function createComponentUploadForm($name)
	{
		$form = new \Nette\Application\UI\Form($this, $name);
		$filesModel = $this->context->models->files;
		$types = $filesModel->getFileTypes()->fetchPairs('id', 'name');
		$form->addText('name', 'Název:');
		$form->addSelect('file_type_id', 'Typ:', $types);
		$form->addUpload('file', 'Soubor:');
		$form->addTextArea('description', 'Popis:', 22, 5);
		$form->addSubmit('save', 'Vložit');
		$form->addHidden('task_id', $this->id);
		if($this->id === null){
			$this->id = $form['task_id']->getValue();
		}
		$form->addHidden('user_id', $this->user->id);
		$form->onSuccess[] = callback($this, 'uploadFormSubmitted');
		return $form;
	}
	
	public function uploadFormSubmitted($form)
	{
		$values = $form->getValues();
		$file = $values->file;
		if ($file->isOk())
		{
			$path = $this->context->params['uploadDir'] . '/task/' . $this->id . '/' . $file->getSanitizedName();
			$file->move($path);
			unset($values['file']);
			$values['path'] = $path;
			if ($this->context->models->files->addTaskFile($values) !== null)
			{
				$this->flashMessage('Soubor byl úspěšně nahrán');
				$this->redirect('this');
			} else
			{
				$this->flashMessage('Chyba při vkládání souboru.', 'error');
			}
		} else
		{
			$this->flashMessage('Chyba při nahrávání souboru.', 'error');
		}
	}
	
	public function actionDownloadFile($id)
	{
		$filesModel = $this->context->models->files;
		$file = $filesModel->getTaskFile($id);
		$response = new \Nette\Application\Responses\FileResponse($file['path']);
		$this->sendResponse($response);
	}
	
	/** @secured */
	public function handleDeleteFile($file)
	{
		if($this->context->models->files->deleteTaskFile($file)){
			$this->flashMessage('Soubor byl smazán');
		}  else
		{
			$this->flashMessage('Nastala chyba při mazání souboru');
		}
		$this->redirect('this');
	}
}
